package com.coldwindblows.blog.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.coldwindblows.blog.constant.WebConst;
import com.coldwindblows.blog.dao.ContentMapper;
import com.coldwindblows.blog.dao.MetaMapper;
import com.coldwindblows.blog.dto.MetaDto;
import com.coldwindblows.blog.dto.Types;
import com.coldwindblows.blog.exception.TipException;
import com.coldwindblows.blog.pojo.ContentDo;
import com.coldwindblows.blog.pojo.MetaDo;
import com.coldwindblows.blog.pojo.RelationshipDo;
import com.coldwindblows.blog.service.IContentService;
import com.coldwindblows.blog.service.IMetaService;
import com.coldwindblows.blog.service.IRelationshipService;

/**
 * 
 * @author Administrator
 *
 */
@Service
public class IMetaServiceImpl implements IMetaService {

	@Autowired
	private MetaMapper metaDao;
	
	@Autowired
	private ContentMapper contentDao;
	
	@Autowired
	private IRelationshipService relationshipService;
	
	@Autowired
	private IContentService contentService;
	
	@Override
	public MetaDto getMeta(String type, String name) {
		if(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(name)) {
			return metaDao.selectMetaDtoByNameAndType(name, type);
		}
		return null;
	}

	@Override
	public Integer countMeta(Integer mid) {
		return contentDao.countByMid(mid);
	}

	@Override
	public List<MetaDo> getMetas(String types) {
		if(StringUtils.isNoneBlank(types)) {
			MetaDo temp = new MetaDo();
			temp.setType(types);
			return metaDao.selectBySelective(temp);
		}
		return null;
	}
	
	@Override
	public List<MetaDto> getMetaList(String type, String orderby, int limit) {
		if(StringUtils.isBlank(type)) {
			return null;
		}
		if(StringUtils.isBlank(orderby)) {
			orderby = "count desc, a.mid desc";
		}
		limit = limit < 1 || limit > WebConst.MAX_POSTS ? 10 : limit;
		MetaDo temp = new MetaDo();
		temp.setType(type);
		
		return metaDao.selectFromSql(temp, orderby, limit);
	}

	@Transactional
	@Override
	public boolean insertMeta(MetaDo meta) {
		if(null != meta) {
			return metaDao.insert(meta) > 0;
		}
		return false;
	}

	@Transactional
	@Override
	public boolean insertMetas(Integer cid, String name, String type) {
		if(null == cid) {
			throw new TipException("项目关联id不能为空");
		}
		if(StringUtils.isNotBlank(name) && StringUtils.isNotBlank(type)) {
			String[] nameArr = StringUtils.split(name, ",");
			for(String nn : nameArr) {
				this.saveOrUpdate(cid, nn, type);
			}
		}
		return true;
	}
	
	private void saveOrUpdate(Integer cid, String name, String type) {
		MetaDo temp = new MetaDo();
		temp.setType(type);
		temp.setName(name);
		List<MetaDo> list = metaDao.selectBySelective(temp);
		
		int mid;
		MetaDo meta;
		if(list.size() == 1) {
			meta = list.get(0);
			mid = meta.getMid();
		} else if(list.size() > 1) {
			throw new TipException("查到多条数据");
		} else {
			meta = new MetaDo();
			meta.setSlug(name);
			meta.setName(name);
			meta.setType(type);
			metaDao.insert(meta);
			mid = meta.getMid();
		}
		
		if(mid != 0) {
			Long count = relationshipService.countById(cid, mid);
			if(count == 0) {
				RelationshipDo rdo = new RelationshipDo();
				rdo.setCid(cid);
				rdo.setMid(mid);
				relationshipService.insert(rdo);
			}
		}
	}

	@Transactional
	@Override
	public boolean insertMeta(String type, String name, Integer mid) {
		if(StringUtils.isBlank(type) || StringUtils.isBlank(name)) {
			return false;
		}
		MetaDo temp = new MetaDo();
		temp.setType(type);
		temp.setName(name);
		List<MetaDo> list = metaDao.selectBySelective(temp);
		if(list.size() != 0) {
			throw new TipException("已存在该项");
		}
		
		temp = new MetaDo();
		temp.setName(name);
		// 判断原先是否存在该项
		boolean exists = false;
		
		if(null != mid) {
			MetaDo original = metaDao.selectByPrimaryKey(mid);
			if(original != null) {
				exists = true;
				temp.setMid(mid);
				metaDao.updateByPrimaryKey(temp);
				// 更新原有文章的categories
				contentService.updateCategory(original.getName(), name);
			}
		}
		
		if(!exists) {
			// 不存在插入一条
			temp.setType(type);
			metaDao.insert(temp);
		}
		
		return true;
	}

	@Transactional
	@Override
	public boolean deleteMeta(Integer mid) {
		MetaDo meta = metaDao.selectByPrimaryKey(mid);
		if(null == meta) {
			return false;
		}
		String type = meta.getType();
		String name = meta.getName();
		metaDao.deleteByPrimaryKey(mid);
		
		List<RelationshipDo> rlist = relationshipService.getRelationshipById(null, mid);
		if(null == rlist) {
			relationshipService.deleteById(null, mid);
			return true;
		}
		ContentDo temp = null;
		ContentDo content = null;
		for(RelationshipDo rdo : rlist) {
			content = contentService.getDetail(String.valueOf(rdo.getCid()));
			if(null == content) {
				continue;
			}
			temp = new ContentDo();
			temp.setCid(rdo.getCid());
			if(type.equals(Types.CATEGORY.getType())) {
				temp.setCategories(reMeta(name, content.getCategories()));
			}
			if(type.equals(Types.TAG.getType())) {
				temp.setTags(reMeta(name, content.getTags()));
			}
			contentService.updateContent(temp);
		}
		relationshipService.deleteById(null, mid);
		return true;
	}

	private String reMeta(String name, String categories) {
		String[] ms = StringUtils.split(categories, ",");
		StringBuilder sbuil = new StringBuilder();
		for(String m : ms) {
			if(!name.equals(m)) {
				sbuil.append(",").append(m);
			}
		}
		if(sbuil.length() > 0) {
			return sbuil.substring(1);
		}
		return "";
	}

	@Transactional
	@Override
	public boolean updateMeta(MetaDo meta) {
		if(null != meta && null != meta.getMid()) {
			return metaDao.updateByPrimaryKey(meta) > 0;
		}
		return false;
	}

}
